//
//  BK_Confirm_Order_VC.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/2/24.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_Confirm_Order_VC.h"
#import "BK_OD_Color.h"
#import "BK_Confirm_Order_Common.h"
#import "Mediator+BKMy.h"
#import "BK_Order_Model.h"
#import "BK_Confirm_Order_Tool.h"




@interface BK_Confirm_Order_VC ()
<
UITableViewDelegate,
UITableViewDataSource,
BK_Confirm_Order_ChooseExpress_HeadViewDelegate,
BK_Confirm_Order_Coupons_Delegate,
BK_Confirm_Order_FooterView_Deleagte
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)BK_Confirm_Order_FooterView *view_footer;
@property(nonatomic, strong)ExceptionView *exceptionView;

@property(nonatomic, strong)NSMutableArray <BK_CO_Section_Model *> *marr_Section;
@property(nonatomic, strong)NSMutableArray <CellModel *> *marr_Express;
@property(nonatomic, strong)NSDictionary *allData;
/*记录选择快递所在的分区*/
@property(nonatomic, assign)NSInteger courierSection;
/*记录选择优惠券所在的分区*/
@property(nonatomic, assign)NSInteger couponSection;

@property(nonatomic, strong)BK_Order_Model * model_order;
@property(nonatomic, strong)BK_orders_dic_Model * model_orders_dic;


@property(nonatomic,assign) BOOL isOpen_Express;
//@property(nonatomic, strong)NSIndexPath *indexPath_Open;



@property(nonatomic, strong) NSString * storeId	;//string	否	小店Id（在goodsinfo里）
@property(nonatomic, strong) NSString * shopKeeper;//	string	否	小店店主账户（在goodsinfo里）

@end

@implementation BK_Confirm_Order_VC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setProperty];
    [self createUI];
    [self check_NetWork];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    /*
     * 防止在用户在点击收货地址   之后然后回来   无选择状态
     */
    if (_isOpen_Express) {
        [self  orderChooseCourierHeadViewDidSelected];

        BK_Confirm_Order_ChooseExpress_Cell_Header *headView = (BK_Confirm_Order_ChooseExpress_Cell_Header *)[self.tableView headerViewForSection:_courierSection];

        [headView doSomethingWithOpen];
    }
    

    [super viewWillDisappear:animated];
    kOrderDismiss;
    
    
    
    
    
}

#pragma mark==================setProperty======================
-(void)setProperty{
    //确认订单页面
    self.navigationItem.title = kOrderLocalizeString(@"BKOrderControllerTitle");
    self.view.backgroundColor = ThemeBackgroundColor;
    _marr_Section = [NSMutableArray array];
    
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    
}

#pragma mark==================createUI======================
-(void)createUI{
    _view_footer = [[BK_Confirm_Order_FooterView alloc] initWithFrame:CGRectZero];
    _view_footer.delegate = self;
    [self.view addSubview:_view_footer];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    [self layoutUI];
}


#pragma mark==================布局======================
- (void)layoutUI{
    [_view_footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
//        make.height.mas_equalTo(44);
        make.height.mas_equalTo(49);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(_view_footer.mas_top).offset(0);
    }];
}
#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            /*
             * 获取用户默认的收货地址
             */
            [self BK_getData_deliver_address_default];
            
        }
            break;
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
#pragma mark==================获取用户默认的收货地址======================
-(void)BK_getData_deliver_address_default{
    __weak typeof(self) weakSelf = self;
    if (self.exceptionView) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    [BK_Confirm_Order_Tool BK_Deliver_Address_Default:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            BKOrderUsedAddress *address = [BKOrderUsedAddress mj_objectWithKeyValues:obj[@"data"]];
            [self create_Marr_Section_From_Deliver_address:address];
            [self BK_getData_Order_Confirm];
        }else{
            [_view_footer setCanSubmit:NO];
            
            if (!weakSelf.exceptionView ) {
                
                ExceptionCodeType codeType;
                if (error) {
                    if (error.code == -1001) {
                        codeType = ExceptionCodeTypeRequestFailed;
                    }else{
                        codeType = ExceptionCodeTypeServerError;
                    }
                }else{
                    codeType = ExceptionCodeTypeServerError;
                }
                
                
                weakSelf.exceptionView = [ExceptionView exceptionViewWithType:codeType];
                weakSelf.exceptionView.backgroundColor = self.view.backgroundColor;
                ExceptionViewAction *action = [ExceptionViewAction actionWithType:codeType handler:^(ExceptionViewAction *action) {
                    [weakSelf BK_getData_deliver_address_default];
                }];
                [weakSelf.exceptionView addAction:action];
                [weakSelf.exceptionView showInView:weakSelf.view];
            }
            
        }
    }];
    
    
}

/*
 * 构建BK_CO_Section_Model的数组
 */
-(void)create_Marr_Section_From_Deliver_address:(BKOrderUsedAddress*)address{
    /*
     * 第一段：放收货地址
     */
    CellModel *c = [[CellModel alloc] init];
    c.className = NSStringFromClass([BK_Confirm_Order_Contact_Cell class]);
    c.reuseIdentifier = @"order_address";
    c.height = [BK_Confirm_Order_Contact_Cell computeHeight:address];
    c.selectorString = @"chooseContact:";
    c.userInfo = address;
    
    BK_CO_Section_Model *s = [BK_CO_Section_Model sectionModelWithTitle:nil cells:@[c]];
    s.headerhHeight = 10;
    s.footerHeight = 10;
    
    [self.marr_Section insertObject:s atIndex:0];
}

/**
 构建BK_CO_Section_Model的数组
 */
- (void)create_Marr_Section_From_Order_Confirm:(id)responseObject{
    
    _model_order = [BK_Order_Model mj_objectWithKeyValues:responseObject[@"data"]];
    _model_orders_dic = _model_order.orders[0];
    
    _allData = responseObject;
    if (_marr_Section.count > 1){
        BK_CO_Section_Model *s0 = _marr_Section.firstObject;
        [_marr_Section removeAllObjects];
        [_marr_Section addObject:s0];
    }
    //    NSString *integralId = _model_orders_dic.integralGoodsId;
    /**
     商品列表
     */
    NSMutableArray *goodsCells = [NSMutableArray array];
    
    for (BK_orders_dic_order_order_items_Model *goods in _model_orders_dic.order_items){
        CellModel *gc = [[CellModel alloc] init];
        gc.className = NSStringFromClass([BK_Confirm_Order_Goods_Cell class]);
        gc.reuseIdentifier = @"goodsInfo";
        gc.height = [BK_Confirm_Order_Goods_Cell computeHeight:goods];
        
        /*
         * 手动赋值
         */
        goods.thNormalType=_model_orders_dic.thNormalType;
        
        gc.userInfo = goods;
        [goodsCells addObject:gc];
    }
    
    
    BK_CO_Section_Model *gs = [BK_CO_Section_Model sectionModelWithTitle:nil cells:goodsCells.copy];
    gs.className = NSStringFromClass([BK_Confirm_Order_Goods_Cell_Header class]);
    gs.reuseIdentifier = @"goodsHeader";
    gs.userInfo = _model_orders_dic.order_deliver_address;
    gs.headerhHeight = [BK_Confirm_Order_Goods_Cell_Header computeHeight:_model_orders_dic.order_deliver_address];
    gs.footerHeight = 10;
    
    [_marr_Section addObject:gs];
    
    //预计发货日期
    NSString *thbuyflag = _model_orders_dic.thNormalType;
    if (thbuyflag && [thbuyflag integerValue] == 1 && _model_orders_dic.lastSendDateZh ) {
        CellModel *dtcm = [[CellModel alloc] init];
        dtcm.className = NSStringFromClass([BK_Confirm_Order_DeliveryTime_Cell class]);
        dtcm.reuseIdentifier = @"deliveryTime";
        dtcm.height = [BK_Confirm_Order_DeliveryTime_Cell computeHeight:nil];
        dtcm.userInfo = @{@"time" : _model_orders_dic.lastSendDateZh};
        
        BK_CO_Section_Model *dtsm = [BK_CO_Section_Model sectionModelWithTitle:@"" cells:@[dtcm]];
        dtsm.headerhHeight = 0.1;
        dtsm.footerHeight = 0.1;
        
        [_marr_Section addObject:dtsm];
    }
    
    //如果不是积分兑换商品
    if (!_model_orders_dic.integralGoodsId || [_model_orders_dic.integralGoodsId isEqualToString:@""]){
        /**
         快递信息
         */
        _marr_Express = [NSMutableArray array];
        CellModel *currentCm;
        
        for (BK_orders_dic_expressCompanyInfo_Model *courier in _model_orders_dic.expressCompanyInfo){
            
            CellModel *cc = [[CellModel alloc] init];
            cc.className = NSStringFromClass([BK_Confirm_Order_ChooseExpress_Cell class]);
            cc.reuseIdentifier = @"courier";
            cc.height = [BK_Confirm_Order_ChooseExpress_Cell computeHeight:courier];
            cc.userInfo = courier;
            cc.selectorString = @"chooseCourier:";
            if ([courier.defaultSelected isEqualToString:@"1"])
            {
                currentCm = cc;
            }
            
            [_marr_Express addObject:cc];
        }
        
        BKOrderCurrentCourier *cCourier = [[BKOrderCurrentCourier alloc] init];
        cCourier.courier = currentCm.userInfo;
        cCourier.count = _marr_Express.count;
        cCourier.index = [_marr_Express indexOfObject:currentCm];
        
        BK_CO_Section_Model *cs = [[BK_CO_Section_Model alloc] init];
        cs.className = NSStringFromClass([BK_Confirm_Order_ChooseExpress_Cell_Header class]);
        cs.reuseIdentifier = @"courierHeader";
        cs.delegate = self;
        cs.userInfo = cCourier;
        cs.headerhHeight = [BK_Confirm_Order_ChooseExpress_Cell_Header computeHeight:cCourier];
        cs.footerHeight = 10;
        
        [_marr_Section addObject:cs];
        _courierSection = _marr_Section.count-1;
        
        /**
         优惠券
         */
        NSMutableArray *couponArr = [NSMutableArray array];
        BK_orders_dic_order_shoppingTicketList_Model *usedCoupon;
        for (BK_orders_dic_order_shoppingTicketList_Model *coupon in _model_orders_dic.shoppingTicketList){
            //选中使用的优惠券
            if ([coupon.selected isEqualToString:@"1"]){
                usedCoupon = coupon;
            }
            
            [couponArr addObject:coupon];
        }
        
        BKOrderCurrentCoupon *cCoupon = [[BKOrderCurrentCoupon alloc] init];
        cCoupon.coupons = couponArr;
        cCoupon.usedCoupon = usedCoupon;
        
        BK_CO_Section_Model *couponM = [[BK_CO_Section_Model alloc] init];
        couponM.className = NSStringFromClass([BK_Confirm_Order_Coupons_Cell_Header class]);
        couponM.reuseIdentifier = @"couponHeader";
        couponM.delegate = self;
        couponM.userInfo = cCoupon;
        couponM.headerhHeight = [BK_Confirm_Order_Coupons_Cell_Header computeHeight:couponM];
        couponM.footerHeight = 10;
        
        [_marr_Section addObject:couponM];
        _couponSection = _marr_Section.count-1;
        
    }
    /**
     价格明细
     */
    NSMutableArray <CellModel *>*priceArr = [NSMutableArray array];
    for (BK_orders_dic_order_amount_lable_list_Model *price in _model_orders_dic.order_amount_lable_list){
        CellModel *cm = [[CellModel alloc] init];
        cm.className  = NSStringFromClass([BK_Confirm_Order_PriceList_Cell class]);
        cm.reuseIdentifier = @"order_price";
        cm.height = [BK_Confirm_Order_PriceList_Cell computeHeight:price];
        cm.userInfo = @{@"price" : price, @"integralGoodsId" : _model_orders_dic.integralGoodsId ? _model_orders_dic.integralGoodsId : @""};
        [priceArr addObject:cm];
    }
    
    //无用 布局model
    CellModel *uc = [[CellModel alloc] init];
    uc.className = NSStringFromClass([BK_Confirm_Order_PriceList_Cell class]);
    uc.height = 10;
    uc.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [priceArr addObject:uc];
    
    BK_CO_Section_Model *ps = [BK_CO_Section_Model sectionModelWithTitle:nil cells:priceArr.copy];
    ps.headerhHeight = 0.1;
    ps.footerHeight  = 10;
    
    [_marr_Section addObject:ps];
    
    /**
     订单金额
     */
    _view_footer.orderPrice = _model_order.orders_amount;
    
}

#pragma mark==================请求订单数据======================
- (void)BK_getData_Order_Confirm{
    NSDictionary *paramDic = [self generateRequestParameter];
    NSString *paramJsonStr = [paramDic mj_JSONString];
    [BK_Confirm_Order_Tool BK_Order_Confirm:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            [self create_Marr_Section_From_Order_Confirm:obj];
            [_tableView reloadData];
            [_view_footer setCanSubmit:YES];
        }else{
            if([obj[@"msg"] isEqualToString:@"所选地址不送达！"]){
                /*
                 * 再重置成功的选择快递
                 */
//                CellModel *cc = [[CellModel alloc] init];
//                cc.className = NSStringFromClass([BK_Confirm_Order_ChooseExpress_Cell class]);
//                cc.reuseIdentifier = @"courier";
//                cc.selectorString = @"chooseCourier:";
//                
//                NSIndexPath *path=[NSIndexPath indexPathForRow:1 inSection:_marr_Section.count-1-2];
//                [self chooseCourier:path];
                
                
            }
            [_tableView reloadData];
            [_view_footer setCanSubmit:NO];
        }
    } WithParamJsonStr:paramJsonStr];
}

#pragma mark==================生成订单请求参数======================
- (NSDictionary *)generateRequestParameter{
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
//    [1]	(null)	@"storeId" : @"1234321"	
    
    
    
    NSMutableDictionary *orderDic = [_arr_order.firstObject mutableCopy];
    //    storeId	string	否	小店Id（在goodsinfo里）
    //    shopKeeper	string	否	小店店主账户（在goodsinfo里）

    if (orderDic[@"shopKeeper"]) {
        _shopKeeper=orderDic[@"shopKeeper"];
    }
    if (orderDic[@"storeId"]) {
        _storeId=orderDic[@"storeId"];
    }
    [paramDic setObject:_arr_order forKey:@"goods_info"];
    
    //兑换商品
    NSString *integralGoodsId = _arr_order.firstObject[@"integralGoodsId"];
    [paramDic setObject:integralGoodsId ? integralGoodsId : @"" forKey:@"integralGoodsId"];
    
    //是否囤货
    NSString *thnormaltype = orderDic[@"thnormaltype"];
    [paramDic setObject:thnormaltype ? thnormaltype : @"" forKey:@"thnormaltype"];
    
    [paramDic setObject:@"" forKey:@"usedShoppingTicketId"];
    
    for (BK_CO_Section_Model *sm in _marr_Section) {
        if (sm.className == nil){
            /**
             地址ID
             */
            CellModel *cm = sm.cells.firstObject;
            if ([cm.className isEqualToString:NSStringFromClass([BK_Confirm_Order_Contact_Cell class])]) {
                BKOrderUsedAddress *address = cm.userInfo;
                NSString *deliver_id = address.deliver_id;
                [paramDic setObject:deliver_id ? deliver_id :@""
                             forKey:@"deliver_id"];
            }
            continue;
        }
        if ([sm.className isEqualToString:NSStringFromClass([BK_Confirm_Order_ChooseExpress_Cell_Header class])]){
            /**
             快递ID
             */
            BK_orders_dic_expressCompanyInfo_Model *courier = [sm.userInfo courier];
            [paramDic setObject:courier.expressCompanyId forKey:@"express_companyid"];
            continue;
        }
        if ([sm.className isEqualToString:NSStringFromClass([BK_Confirm_Order_Coupons_Cell_Header class])]){
            /**
             优惠券ID
             */
            NSString * shoppingTicketId;
            BKOrderCurrentCoupon *cCoupon = sm.userInfo;
            if (cCoupon.usedCoupon == nil) {
                shoppingTicketId = @"-1";
            }else{
                BK_orders_dic_order_shoppingTicketList_Model *coupon = cCoupon.usedCoupon;
                shoppingTicketId = coupon.userCouponId;
            }
            [paramDic setObject:shoppingTicketId forKey:@"usedShoppingTicketId"];
            continue;
        }
    }
    
    
    
    return paramDic;
}



#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    BK_CO_Section_Model *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    BK_CO_Section_Model *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    BK_CO_Section_Model *sm = _marr_Section[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BK_CO_Section_Model *sm = _marr_Section[section];
    BK_Confirm_Order_Cell_HeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:sm.reuseIdentifier];
    if (!headerView) {
        headerView = [[NSClassFromString(sm.className) alloc] initWithReuseIdentifier:sm.reuseIdentifier];
    }
    return headerView;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    BK_CO_Section_Model *sm = _marr_Section[section];
    BK_Confirm_Order_Cell_HeaderFooterView *headerView = (BK_Confirm_Order_Cell_HeaderFooterView *)view;
    
    headerView.delegate = sm.delegate;
    
    SEL selector = @selector(fillData:);
    if ([headerView respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [headerView performSelector:selector withObject:sm.userInfo];
#pragma clang diagnostic pop
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BK_CO_Section_Model *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BK_CO_Section_Model *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    BK_Confirm_Order_Cell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    
    cell.selectionStyle = cm.selectionStyle;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BK_CO_Section_Model *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    BK_Confirm_Order_Cell *cellzz = (BK_Confirm_Order_Cell *)cell;
    
    SEL fillData = @selector(fillData:);
    if ([cellzz respondsToSelector:fillData]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [cellzz performSelector:fillData withObject:cm.userInfo];
#pragma clang diagnostic pop
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BK_CO_Section_Model *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    NSString *selectString = cm.selectorString;
    if (selectString) {
        SEL selector = NSSelectorFromString(selectString);
        if ([self respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
            [self performSelector:selector withObject:indexPath];
#pragma clang diagnostic pop
        }
    }
    
}

#pragma section 点击事件
#pragma mark==================快递选择======================
-(void)orderChooseCourierHeadViewDidSelected{
    
    
    
    
    
    
    BK_CO_Section_Model *sm = _marr_Section[_courierSection];
    BKOrderCurrentCourier *cCourier = sm.userInfo;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < _marr_Express.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:_courierSection];
        [array addObject:indexPath];
    }
    
    if(!sm.isExpand) {
        if (!_marr_Express.count) {
            return;
        }
        sm.cells = _marr_Express;
        [_tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:cCourier.index inSection:_courierSection] animated:YES scrollPosition:UITableViewScrollPositionNone];
        
        /*
         * 快递打开
         */
        _isOpen_Express=YES;
        
    } else {
        sm.cells = nil;
        [_tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];
        /*
         * 快递关闭
         */
        _isOpen_Express=NO;
    }
    
    sm.isExpand = !sm.isExpand;
}


#pragma mark==================优惠券选择======================
- (void)BK_Confirm_Order_Coupons_DidSelected:(BK_Confirm_Order_Coupons_Cell_Header *)couponsHeadView{
    
    __weak typeof(self)weakSelf = self;
    BK_CO_Section_Model *sm = _marr_Section[_couponSection];
    BKOrderCurrentCoupon *cCoupon = sm.userInfo;
    
    BKOrderCouponsViewController *couponsVC = [[BKOrderCouponsViewController alloc] init];
    couponsVC.cCoupon = cCoupon;
    couponsVC.orderParamDic = [self generateRequestParameter];
    couponsVC.block = ^(BKOrderCurrentCoupon *currentCoupon){//选择购物券完成后的回调
        sm.userInfo = currentCoupon;
        [weakSelf BK_getData_Order_Confirm];
    };
    
    [self.navigationController pushViewController:couponsVC animated:YES];
}

#pragma cell 点击事件
#pragma mark==================选择收货地址======================
- (void)chooseContact:(NSIndexPath *)indexPath{
    
    __weak typeof(self) weakSelf = self;
    BK_CO_Section_Model *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    BKOrderUsedAddress *address = cm.userInfo;
    
    BKODAddressViewController *addressVC = [[BKODAddressViewController alloc] init];
    addressVC.use_address = address;
    addressVC.block = ^(BKOrderUsedAddress *usedAds){
        cm.userInfo = usedAds;
        cm.height = [BK_Confirm_Order_Contact_Cell computeHeight:usedAds];
        [weakSelf BK_getData_Order_Confirm];
    };
    [self.navigationController pushViewController:addressVC animated:YES];
}

#pragma mark==================快递选择======================
- (void)chooseCourier:(NSIndexPath *)indexPath{
    
    BK_CO_Section_Model *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row]; 
    BK_orders_dic_expressCompanyInfo_Model *courier = cm.userInfo;
    
//    BK_Confirm_Order_ChooseExpress_Cell_Header *headView = (BK_Confirm_Order_ChooseExpress_Cell_Header *)[self.tableView headerViewForSection:indexPath.section];
//    [headView changeCourierName:courier.expressCompanyName];
//    [self orderChooseCourierHeadViewDidSelected];
    
    BKOrderCurrentCourier *cCourier = sm.userInfo;

    if (cCourier.index == indexPath.row) {
        return;
    }
    /*
     * 回传上一次选中的快递-----可以送达的
     */
    BKOrderCurrentCourier *OK_cCourier = [[BKOrderCurrentCourier alloc]init];
    OK_cCourier.count=cCourier.count;
    OK_cCourier.courier = cCourier.courier;
    OK_cCourier.index = cCourier.index;
 //==============================================
    
    /*
     * 赋值
     */
    cCourier.count = _marr_Express.count;
    cCourier.courier = courier;
    cCourier.index = indexPath.row;
    

    NSDictionary *paramDic = [self generateRequestParameter];
    NSString *paramJsonStr = [paramDic mj_JSONString];
    [BK_Confirm_Order_Tool BK_Order_Confirm:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            
            
            BK_Confirm_Order_ChooseExpress_Cell_Header *headView = (BK_Confirm_Order_ChooseExpress_Cell_Header *)[self.tableView headerViewForSection:indexPath.section];
            
            [headView changeCourierName:courier.expressCompanyName];
            
            [self orderChooseCourierHeadViewDidSelected];
            
            
            
            [self create_Marr_Section_From_Order_Confirm:obj];
            [_tableView reloadData];
            [_view_footer setCanSubmit:YES];
        }else{
            if([obj[@"msg"] rangeOfString:@"地址不送达"].location !=NSNotFound){
            
                /*
                 * 再重置成功的选择快递
                 */
                cCourier.count = OK_cCourier.count;
                cCourier.courier = OK_cCourier.courier;
                cCourier.index = OK_cCourier.index;
                
                
                 /*
                 * 回收箭头
                 */
                BK_Confirm_Order_ChooseExpress_Cell_Header *headView = (BK_Confirm_Order_ChooseExpress_Cell_Header *)[self.tableView headerViewForSection:indexPath.section];
                
                [headView doSomethingWithOpen];
                
                
                /*
                 * 回收展示
                 */
                [self orderChooseCourierHeadViewDidSelected];
                
            }else{
                BK_Confirm_Order_ChooseExpress_Cell_Header *headView = (BK_Confirm_Order_ChooseExpress_Cell_Header *)[self.tableView headerViewForSection:indexPath.section];
                
                [headView changeCourierName:courier.expressCompanyName];
                
                [self orderChooseCourierHeadViewDidSelected];
                
                
                
                [self create_Marr_Section_From_Order_Confirm:obj];
                [_tableView reloadData];
                [_view_footer setCanSubmit:NO];
            }

            
        }
    } WithParamJsonStr:paramJsonStr];
    
    
}


#pragma mark==================提交订单======================
- (void)BK_Confirm_Order_FooterView_DidSelected:(BK_Confirm_Order_FooterView *)footerView{
    NSDictionary *paramDic = [self generateSubmitOrdersInTheDictionary];
    NSString *paramJsonStr = [paramDic mj_JSONString];
    [BK_Confirm_Order_Tool BK_Order_Submit:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            UIViewController *paymentVC = [[Mediator sharedInstance] BKOrder_paymentViewControllerWithParameter:@{@"globalStatus" : obj[@"data"][@"global_status"], @"orderNumber" : [obj[@"data"][@"order_list"] firstObject]}];
            NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
            for (UIViewController *vc in self.navigationController.viewControllers) {
                if ([vc isKindOfClass:[self class]]) {
                    [viewControllers removeObject:vc];
                }
            }
            [viewControllers addObject:paymentVC];
            [self.navigationController setViewControllers:[NSArray arrayWithArray:viewControllers] animated:YES];
        }
    } WithParamJsonStr:paramJsonStr];
    
}

#pragma mark================== 生成提交订单所需的字典======================
- (NSDictionary *)generateSubmitOrdersInTheDictionary{
    
    if ([_allData[@"success"] boolValue] == NO) {
        return nil;
    }
    
    NSString *thnormaltype = _model_orders_dic.thNormalType;
    thnormaltype = thnormaltype ? thnormaltype : @"";
    
    NSString *integralGoodsId = _model_orders_dic.integralGoodsId ;
    integralGoodsId = integralGoodsId ? integralGoodsId : @"";
    
    NSMutableArray *orders_infoArr = [NSMutableArray array];
    
    NSArray *orderArr = _allData[@"data"][@"orders"];
    for (NSDictionary *orderDic in orderArr){
        
        NSString *usedShoppingTicketId = @"";
        for (NSDictionary *shoppingTickeDic in orderDic[@"shoppingTicketList"]){
            if ([shoppingTickeDic[@"selected"] isEqualToString:@"1"]) {
                usedShoppingTicketId = shoppingTickeDic[@"userCouponId"];
            }
        }
        
        NSMutableArray *goods_infoArr = [NSMutableArray array];
//        if (_storeId&&_shopKeeper) {
        
            for (NSDictionary *orderItemsDic in orderDic[@"order_items"]){
                
                NSDictionary *goods_infoDic ;
                if (orderItemsDic[@"storeId"]&&[[NSString stringWithFormat:@"%@",orderItemsDic[@"storeId"]] length]>0  && orderItemsDic[@"shopKeeper"]&&[[NSString stringWithFormat:@"%@",orderItemsDic[@"shopKeeper"]] length]>0) {
                    goods_infoDic = @{@"amount"            : orderItemsDic[@"goods_amount"],
                                      @"goods_id"          : orderItemsDic[@"goods_id"],
                                      @"goods_reserve_id"  : orderItemsDic[@"goods_reserve_id"],
                                      @"userPrice"         : orderItemsDic[@"userPrice"],
                                      @"sendDate"          : orderItemsDic[@"goods_send_date"],
                                      
                                      
                                      
                                      
                                      
                                      @"storeId"           : orderItemsDic[@"storeId"],
                                      @"shopKeeper"        : orderItemsDic[@"shopKeeper"]
                                      
                                      
                                      };
                }else{
                    goods_infoDic = @{@"amount"            : orderItemsDic[@"goods_amount"],
                                      @"goods_id"          : orderItemsDic[@"goods_id"],
                                      @"goods_reserve_id"  : orderItemsDic[@"goods_reserve_id"],
                                      @"userPrice"         : orderItemsDic[@"userPrice"],
                                      @"sendDate"          : orderItemsDic[@"goods_send_date"],
                                      
                                      
                            
                                      
                                      
                                      };
                }
                
                
                
               
                
                [goods_infoArr addObject:goods_infoDic];
            }
//        }else{
//            for (NSDictionary *orderItemsDic in orderDic[@"order_items"]){
//                NSDictionary *goods_infoDic = @{@"amount"            : orderItemsDic[@"goods_amount"],
//                                                @"goods_id"          : orderItemsDic[@"goods_id"],
//                                                @"goods_reserve_id"  : orderItemsDic[@"goods_reserve_id"],
//                                                @"userPrice"         : orderItemsDic[@"userPrice"],
//                                                @"sendDate"          : orderItemsDic[@"goods_send_date"]
//                                                
//                                                };
//                
//                [goods_infoArr addObject:goods_infoDic];
//            }
//        }

        
        NSDictionary *orders_infoDic;
        if (_storeId&&_shopKeeper) {
            orders_infoDic= @{@"usedShoppingTicketId" : usedShoppingTicketId,
                              @"deliver_address"      : orderDic[@"deliver_code"],
                              @"express_companyid"    : orderDic[@"express_companyid"],
                              @"goods_info"           : goods_infoArr,
                              @"thnormaltype"         : thnormaltype,
                              @"integralGoodsId"      : integralGoodsId,
                              
                              
                              


                              
                              };
            
        }else{
            orders_infoDic= @{@"usedShoppingTicketId" : usedShoppingTicketId,
                              @"deliver_address"      : orderDic[@"deliver_code"],
                              @"express_companyid"    : orderDic[@"express_companyid"],
                              @"goods_info"           : goods_infoArr,
                              @"thnormaltype"         : thnormaltype,
                              @"integralGoodsId"      : integralGoodsId
                              };
        }
        
        
        [orders_infoArr addObject:orders_infoDic];
    }

    
    
    BK_CO_Section_Model *sm = _marr_Section.firstObject;
    CellModel *cm = sm.cells.firstObject;
    BKOrderUsedAddress *address = cm.userInfo;
    NSDictionary *paramDic;
  
                      paramDic = @{@"deliver_id"        : address.deliver_id ? address.deliver_id : @"",
                                   @"orders_info"       : orders_infoArr.copy,
                                   @"source_code"       : @"3",
                                   @"identitycardname"  : @"",
                                   @"identitycardno"    : @"",
                                   @"thnormaltype"      : thnormaltype
                                   };
  
    
    
    return paramDic;
}
@end












































